﻿Public Class FrmMotoMAJ
    Public pDate As Date

    Private szSQL As String
    Private rs As ADODB.Recordset
    Private m_SortingColumn As ColumnHeader
    Private m_SortingIndex As Integer = 0

    Private Sub FrmMotoMAJ_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Me.Text = LibelleMoto(gTypePlanning) & " du " & pDate & " - " & gGroupe
        ' planning moto ?
        If gTypePlanning = "A" Then
            GB_ROUTE.Visible = True
            GB_PLATEAU.Text = "Places Plateau"
        Else
            GB_ROUTE.Visible = False
            GB_PLATEAU.Text = "Nb de places"
        End If

        MotosToScreen()
        InitListeInscrits(0)

    End Sub

    Private Sub MotosToScreen()

        ' Lire le planning sélectionné
        szSQL = "CALL spGet_PLA_MOTO('" & gTypePlanning & "','" & Format(pDate, "yyyy/MM/dd") & "','" & gGroupe & "')"
        GetRecordset(ctDSN_AEM, szSQL, rs)
        If rs.RecordCount > 0 Then
            TE_GROUPE.Text = rs.Fields("groupe").Value
            TE_TOTAL.Value = rs.Fields("total").Value
            TE_ROUTE.Value = rs.Fields("route").Value
            TE_LIBELLE.Text = nv(rs.Fields("libelle").Value)
            TE_MODIFIE_LE.Text = setModifiedBy(rs.Fields("cree_le").Value, rs.Fields("modif_le").Value, rs.Fields("cd_uti").Value)
            If nv(rs.Fields("valide").Value) = "O" Or gUserAcces < 9 Then
                BO_ENREGISTRER.Enabled = False
                BO_SUPPRIMER.Enabled = False
                TE_TOTAL.Enabled = False
                TE_ROUTE.Enabled = False
            Else
                BO_ENREGISTRER.Enabled = True
                BO_SUPPRIMER.Enabled = True
                TE_TOTAL.Enabled = True
                TE_ROUTE.Enabled = True
            End If
            If nv(rs.Fields("valide").Value) = "O" Or gUserAcces < 4 Then
                BO_VALIDER.Enabled = False
            Else
                BO_VALIDER.Enabled = True
            End If
        End If

        rs.Close()

    End Sub

    Private Sub InitListeInscrits(ByVal ix As Integer)
        Dim rsEleve As ADODB.Recordset = Nothing
        Dim nb As Integer = 0

        ' effacer la listview
        LV_INSCRITS.Items.Clear()
        LV_INSCRITS.ListViewItemSorter = Nothing
        TE_INSCRITS.Value = 0
        TE_INSCRITS_ROUTE.Value = 0
        ' Lire la table EXAMENS_AFF
        szSQL = "CALL spGet_PLA_MOTO_LIGNES('" & gTypePlanning & "','" & Format(pDate, "yyyy/MM/dd") & "','" & gGroupe & "',0)"
        GetRecordset(ctDSN_AEM, szSQL, rs)

        Do While Not rs.EOF
            LV_INSCRITS.Items.Add(nv(rs.Fields("cd_mon").Value))
            LV_INSCRITS.Items(nb).SubItems.Add(nv(rs.Fields("cd_cli").Value))
            LV_INSCRITS.Items(nb).SubItems.Add(nv(rs.Fields("nom").Value))

            ' Lire la fiche Eleves
            szSQL = "CALL spGet_ELEVES_byCD_CLI(" & nv(rs.Fields("cd_cli").Value) & ")"
            GetRecordset(ctDSN_AEM, szSQL, rsEleve)
            If rsEleve.RecordCount > 0 Then
                ' calcule le solde
                LV_INSCRITS.Items(nb).SubItems.Add(Zero2Space(rsEleve.Fields("credit").Value - rsEleve.Fields("debit").Value))
                LV_INSCRITS.Items(nb).SubItems.Add(rsEleve.Fields("permis_demande").Value)
            Else
                LV_INSCRITS.Items(nb).SubItems.Add(" ")
                LV_INSCRITS.Items(nb).SubItems.Add(" ")
            End If
            rsEleve.Close()

            If rs.Fields("route").Value = 0 Then
                LV_INSCRITS.Items(nb).SubItems.Add(rs.Fields("qte").Value)
            Else
                LV_INSCRITS.Items(nb).SubItems.Add(rs.Fields("qte").Value & " R")   ' heure de route
            End If
            LV_INSCRITS.Items(nb).SubItems.Add(nv(rs.Fields("comment").Value))
            LV_INSCRITS.Items(nb).SubItems.Add(nv(rs.Fields("lieu").Value))
            If nv(rs.Fields("valide").Value) = "O" Then
                LV_INSCRITS.Items(nb).ForeColor = Color.Green
            Else
                If rs.Fields("statut").Value > 1 Then
                    LV_INSCRITS.Items(nb).ForeColor = Color.Red
                End If
            End If
            If rs.Fields("route").Value = 0 Then
                TE_INSCRITS.Value = TE_INSCRITS.Value + 1
            Else
                TE_INSCRITS_ROUTE.Value = TE_INSCRITS_ROUTE.Value + 1
            End If
            rs.MoveNext()
            nb = nb + 1
        Loop
        ' Close the recordset AND connection.
        rs.Close()

        ' restaurer l'ancienne ordre de tri de la listview
        If m_SortingIndex > 0 Then
            SortListView(LV_INSCRITS, m_SortingColumn, m_SortingIndex)
        End If
        ' restaurer la position du curseur avant le init
        setIndice(ix, LV_INSCRITS)
        ' maj l'entete
        szSQL = "CALL spUpd_PLA_MOTO('" & gTypePlanning & "','" & Format(pDate, "yyyy/MM/dd") & "','" & gGroupe & "'," & _
                 TE_TOTAL.Value & "," & TE_ROUTE.Value & ",'" & TE_LIBELLE.Text & "'," & _
                 gUserAgence & ",'" & gUserCode & "')"
        ExecQuery(ctDSN_AEM, szSQL)


    End Sub

    Private Sub LV_INSCRITS_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles LV_INSCRITS.ColumnClick
        SortListView(LV_INSCRITS, m_SortingColumn, e.Column)
        m_SortingIndex = e.Column
    End Sub

    Private Sub LV_INSCRITS_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles LV_INSCRITS.DoubleClick

        If LV_INSCRITS.SelectedItems.Count > 0 Then
            ' afficher les détails de la ligne NoLigne
            FrmMotoLigne.pDate = pDate
            FrmMotoLigne.pCD_CLI = LV_INSCRITS.SelectedItems(0).SubItems(1).Text
            FrmMotoLigne.pDispo = TE_TOTAL.Value - TE_INSCRITS.Value
            FrmMotoLigne.pDispoRoute = TE_ROUTE.Value - TE_INSCRITS_ROUTE.Value
            FrmMotoLigne.ShowDialog()
            ' réaffiche la viewlist
            InitListeInscrits(LV_INSCRITS.SelectedItems(0).Index)
        End If

    End Sub

    Private Sub LV_INSCRITS_ItemSelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.ListViewItemSelectionChangedEventArgs) Handles LV_INSCRITS.ItemSelectionChanged
        If LV_INSCRITS.SelectedItems.Count > 0 Then
            gCD_CLI = LV_INSCRITS.SelectedItems(0).SubItems(1).Text
        End If

    End Sub

    Private Sub LV_INSCRITS_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles LV_INSCRITS.KeyDown

        Select Case e.KeyCode
            Case Keys.Enter         ' Enter = DoubleClick
                LV_INSCRITS_DoubleClick(sender, e)

            Case Keys.Insert        ' Insert = ' Ajouter un élève
                BO_ADD_LIGNE_Click(sender, e)

        End Select

    End Sub

    Private Sub BO_ADD_LIGNE_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BO_ADD_LIGNE.Click
        ' utilisateur autorisé à créer ?
        If IsUserAuthorised(6) = False Then
            Exit Sub
        End If

        If TE_TOTAL.Value + TE_ROUTE.Value <= TE_INSCRITS.Value + TE_INSCRITS_ROUTE.Value Then
            MsgBox("Plus de place disponibles dans ce planning", MsgBoxStyle.Critical)
            Exit Sub
        End If

        ' afficher les détails de la ligne NoLigne pour création
        FrmMotoLigne.pDate = pDate
        FrmMotoLigne.pCD_CLI = 0
        FrmMotoLigne.pDispo = TE_TOTAL.Value - TE_INSCRITS.Value
        FrmMotoLigne.pDispoRoute = TE_ROUTE.Value - TE_INSCRITS_ROUTE.Value
        FrmMotoLigne.ShowDialog()
        ' réaffiche la viewlist
        InitListeInscrits(0)
    End Sub

    Private Sub BO_SUPPRIMER_Click(sender As System.Object, e As System.EventArgs) Handles BO_SUPPRIMER.Click

        ' planning déjà comptabilisé ?
        If TE_INSCRITS.Value + TE_INSCRITS_ROUTE.Value > 0 Then
            MsgBox("Planning non vide, suppression impossible.", MsgBoxStyle.Critical)
        Else
            ' suppression
            If deleteEnregistrement("pla_moto", Me.Text, gTypePlanning, Format(pDate, "yyyy/MM/dd"), gGroupe) Then
                Me.Close()
            End If
        End If

    End Sub

    Private Sub BO_IMPRIMER_Click_1(sender As System.Object, e As System.EventArgs) Handles BO_IMPRIMER.Click

        ' Editions des états de la rubrique
        gDate_debut = pDate
        FrmEditions.pRubrique = "MOTO"
        FrmEditions.pParametres = ""
        FrmEditions.ShowDialog()

    End Sub

    Private Sub BO_ENREGISTRER_Click_1(sender As System.Object, e As System.EventArgs) Handles BO_ENREGISTRER.Click

        If TE_TOTAL.Value < TE_INSCRITS.Value Or TE_ROUTE.Value < TE_INSCRITS_ROUTE.Value Then
            MsgBox("Le nombre d'inscrits ne peut pas dépasser le nombre total de places", MsgBoxStyle.Critical)
            TE_TOTAL.Focus()
            Exit Sub
        End If

        ' mise à jour 
        szSQL = "CALL spUpd_PLA_MOTO('" & gTypePlanning & "','" & Format(pDate, "yyyy/MM/dd") & "','" & gGroupe & "'," & _
                 TE_TOTAL.Value & "," & TE_ROUTE.Value & ",'" & TE_LIBELLE.Text & "'," & _
                 gUserAgence & ",'" & gUserCode & "')"
        If ExecQuery(ctDSN_AEM, szSQL) Then
            ' fermer la fenetre
            Me.Close()
        End If

    End Sub

    Private Sub BO_CARNET_RDV_Click(sender As System.Object, e As System.EventArgs) Handles BO_CARNET_RDV.Click

        If gCD_CLI > 0 Then
            ' imprimer le carnet de rdv Moto
            FrmViewReport.pCodeEtat = 5
            FrmViewReport.pParamRPT = ""
            FrmViewReport.ShowDialog()
        Else
            MsgBox("Veuillez sélectionner d'abord un élève à imprimer!")
        End If

    End Sub

    Private Sub BO_VALIDER_Click(sender As System.Object, e As System.EventArgs) Handles BO_VALIDER.Click

        Dim nStatut As Integer

        If MsgBox("Après la validation, aucune modification ne sera possible." & vbNewLine & _
                  "Voulez-vous valider le planning du " & pDate & " ?", MsgBoxStyle.OkCancel, _
          "Validation du planning") = MsgBoxResult.Cancel Then
            Exit Sub
        End If

        ' Y-a-t-il des élèves provisoires dans ce planning
        If PlanningHasPending(gTypePlanning, Format(pDate, "yyyy/MM/dd"), gGroupe) = True Then
            MsgBox("Il y a un ou des élèves provisoires dans ce planning. Validation impossible.", vbCritical)
            Exit Sub
        End If

        ' Lire les élèves inscrits dans ce planning
        szSQL = "CALL spGet_PLA_MOTO_LIGNES('" & gTypePlanning & "','" & Format(pDate, "yyyy/MM/dd") & "','" & gGroupe & "',0)"
        GetRecordset(ctDSN_AEM, szSQL, rs)
        Me.Cursor = Cursors.WaitCursor

        Do While Not rs.EOF
            ' Lire l'élève sélectionné
            gCD_CLI = rs.Fields("cd_cli").Value

            nStatut = rs.Fields("statut").Value
            If nStatut = 0 Then
                nStatut = 1
            End If

            ' mettre le rdv dans le compte Eleve 
            If UpdateHeureMoto(gTypePlanning, pDate, rs.Fields("groupe").Value, nStatut, "V") Then
                ' marquer statut de la ligne à validé
                szSQL = "UPDATE pla_moto_lignes set valide='O', statut=" & nStatut & _
                         " WHERE type='" & gTypePlanning & "' AND date='" & Format(pDate, "yyyy/MM/dd") & _
                         "' AND groupe='" & rs.Fields("groupe").Value & "' AND cd_cli=" & gCD_CLI
                ExecQuery(ctDSN_AEM, szSQL)
            End If

            ' élève suivant
            rs.MoveNext()
        Loop
        rs.Close()

        ' marquer statut du stage à validé
        szSQL = "UPDATE pla_moto set valide='O', agence=" & gUserAgence & ", cd_uti='" & gUserCode & _
                 "' WHERE type='" & gTypePlanning & "' AND date='" & Format(pDate, "yyyy/MM/dd") & "' AND groupe='" & gGroupe & "'"
        ExecQuery(ctDSN_AEM, szSQL)
        Me.Cursor = Cursors.Default

        ' réaffiche la liste des inscrits
        InitListeInscrits(0)


    End Sub
End Class